import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import LoginMobile from '@/views/LoginMobile.vue'
import RefundTaskManagementMobile from '@/views/RefundTaskManagementMobile.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: LoginMobile,
    meta: { 
      requiresAuth: false,
      title: '登录'
    }
  },
  {
    path: '/',
    name: 'RefundTaskManagement',
    component: RefundTaskManagementMobile,
    meta: { requiresAuth: true, title: '退款任务管理' }
  }
]

const router = createRouter({
  history: createWebHistory('/refundtask/'),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()
  
  // 如果要去登录页面，直接放行
  if (to.path === '/login') {
    // 如果已经认证，重定向到首页
    if (authStore.isAuthenticated) {
      next('/')
    } else {
      next()
    }
    return
  }
  
  // 如果需要认证但未认证，重定向到登录页面
  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    next('/login')
  } else {
    next()
  }
})

export default router